{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "vscode": {
     "languageId": "plaintext"
    }
   },
   "source": [
    "# YepCode Executor: Serverless Code Execution for AG2 Agents\n",
    "\n",
    "This notebook demonstrates how to use the YepCode Executor with AG2 agents for secure, scalable serverless code execution. YepCode provides production-grade sandboxes that can run Python and JavaScript code with automatic dependency management.\n",
    "\n",
    "## Key Benefits\n",
    "\n",
    "- **Serverless Execution**: No need to manage infrastructure\n",
    "- **Secure Sandboxes**: Code runs in isolated, secure environments\n",
    "- **Automatic Dependencies**: NPM and PyPI packages are installed automatically\n",
    "- **Multi-Language Support**: Python and JavaScript execution\n",
    "- **Production Ready**: Built for enterprise-scale applications\n",
    "\n",
    "## Prerequisites\n",
    "\n",
    "1. Install AG2 with YepCode support:\n",
    "   ```bash\n",
    "   pip install ag2[yepcode]\n",
    "   ```\n",
    "\n",
    "2. Get a YepCode API token from [yepcode.io](https://cloud.yepcode.io)\n",
    "\n",
    "3. Set your API tokens as environment variables:\n",
    "   ```bash\n",
    "   export YEPCODE_API_TOKEN=your_yepcode_token\n",
    "   export OPENAI_API_KEY=your_openai_key  # or other LLM provider\n",
    "   ```\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "from autogen import ConversableAgent, LLMConfig\n",
    "from autogen.coding import YepCodeCodeExecutor\n",
    "\n",
    "# Ensure you have your API tokens set\n",
    "assert os.getenv(\"YEPCODE_API_TOKEN\"), \"Please set YEPCODE_API_TOKEN environment variable\"\n",
    "assert os.getenv(\"OPENAI_API_KEY\"), \"Please set OPENAI_API_KEY environment variable (or configure another LLM provider)\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Example 1: Basic YepCode Executor Setup\n",
    "\n",
    "First, let's create a basic YepCode executor and test it with a simple code execution task.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Initialize YepCode executor\n",
    "yepcode_executor = YepCodeCodeExecutor(\n",
    "    timeout=120,  # Timeout in seconds\n",
    "    remove_on_done=False,  # Keep execution logs for debugging\n",
    "    sync_execution=True,  # Wait for execution to complete\n",
    ")\n",
    "\n",
    "# Create an agent with YepCode executor\n",
    "code_executor_agent = ConversableAgent(\n",
    "    \"code_executor_agent\",\n",
    "    llm_config=False,  # Turn off LLM for this agent\n",
    "    code_execution_config={\"executor\": yepcode_executor},\n",
    "    human_input_mode=\"NEVER\",\n",
    ")\n",
    "\n",
    "print(\"YepCode executor agent created successfully!\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Test basic Python execution\n",
    "task = \"\"\"\n",
    "Run this Python code:\n",
    "```python\n",
    "import datetime\n",
    "import math\n",
    "\n",
    "now = datetime.datetime.now()\n",
    "print(f\"Current time: {now}\")\n",
    "print(f\"Square root of 144: {math.sqrt(144)}\")\n",
    "\n",
    "# Return a message\n",
    "return \"Hello from YepCode serverless execution!\"\n",
    "```\n",
    "\"\"\"\n",
    "\n",
    "reply = code_executor_agent.generate_reply(messages=[{\"role\": \"user\", \"content\": task}])\n",
    "print(reply)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Example 2: Complete AI Agent with YepCode\n",
    "\n",
    "Now let's create a complete setup with an AI assistant that can write and execute code using YepCode.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Configure LLM (using OpenAI as example)\n",
    "llm_config = LLMConfig(\n",
    "    model=\"gpt-5-nano\",\n",
    "    api_key=os.environ[\"OPENAI_API_KEY\"],\n",
    ")\n",
    "\n",
    "# Create code writer agent\n",
    "code_writer_system_message = \"\"\"\n",
    "You are a helpful AI assistant that writes and executes code using YepCode's serverless platform.\n",
    "When writing code:\n",
    "1. Use Python or JavaScript as appropriate for the task\n",
    "2. Include all necessary imports and dependencies (they will be installed automatically)\n",
    "3. Write complete, executable code blocks\n",
    "4. Return meaningful results using 'return' statements\n",
    "5. Add informative print/console.log statements to show progress\n",
    "\n",
    "For data analysis tasks, prefer Python with pandas, numpy, matplotlib, etc.\n",
    "For web scraping or API calls, you can use either Python (requests, beautifulsoup) or JavaScript (axios, cheerio).\n",
    "\n",
    "Always wrap your code in appropriate code blocks with language specification.\n",
    "Reply 'TERMINATE' when the task is completed successfully.\n",
    "\"\"\"\n",
    "\n",
    "with llm_config:\n",
    "    code_writer_agent = ConversableAgent(\n",
    "        \"code_writer_agent\",\n",
    "        system_message=code_writer_system_message,\n",
    "        max_consecutive_auto_reply=5,\n",
    "        code_execution_config=False,  # This agent writes code but doesn't execute it\n",
    "    )\n",
    "\n",
    "# Update code executor agent to work with the writer\n",
    "code_executor_agent = ConversableAgent(\n",
    "    \"code_executor_agent\",\n",
    "    llm_config=False,\n",
    "    code_execution_config={\"executor\": yepcode_executor},\n",
    "    human_input_mode=\"NEVER\",\n",
    "    is_termination_msg=lambda x: x.get(\"content\", \"\").rstrip().endswith(\"TERMINATE\"),\n",
    ")\n",
    "\n",
    "print(\"AI coding team with YepCode executor ready!\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Data Analysis Example\n",
    "\n",
    "Let's ask our AI agent to perform some data analysis using Python libraries.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data_analysis_task = \"\"\"\n",
    "Create a dataset of 100 random sales records with the following columns:\n",
    "- date (random dates from the last 12 months)\n",
    "- product_category (choose from: Electronics, Clothing, Books, Home, Sports)\n",
    "- sales_amount (random amounts between $10 and $500)\n",
    "- region (choose from: North, South, East, West)\n",
    "\n",
    "Then perform the following analysis:\n",
    "1. Calculate total sales by category\n",
    "2. Find the average sales amount by region\n",
    "3. Identify the top-selling month\n",
    "4. Create a summary report\n",
    "\n",
    "Present the results in a clear, formatted output.\n",
    "\"\"\"\n",
    "\n",
    "chat_result = code_executor_agent.initiate_chat(\n",
    "    code_writer_agent,\n",
    "    message=data_analysis_task,\n",
    "    max_turns=10,\n",
    ")\n",
    "\n",
    "print(\"\\n\" + \"=\" * 50)\n",
    "print(\"Data Analysis Task Completed!\")\n",
    "print(\"=\" * 50)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### API Integration Example\n",
    "\n",
    "Now let's demonstrate fetching and analyzing data from a public API.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "api_task = \"\"\"\n",
    "Fetch cryptocurrency data from the CoinGecko API and analyze it:\n",
    "\n",
    "1. Get the current price data for the top 5 cryptocurrencies by market cap\n",
    "2. Calculate the total market cap of these top 5 coins\n",
    "3. Find which coins have gained or lost the most in the last 24 hours\n",
    "4. Create a formatted summary table showing:\n",
    "   - Coin name and symbol\n",
    "   - Current price (USD)\n",
    "   - 24h price change (%)\n",
    "   - Market cap\n",
    "\n",
    "Use the CoinGecko API: https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=5&page=1\n",
    "\"\"\"\n",
    "\n",
    "chat_result = code_executor_agent.initiate_chat(\n",
    "    code_writer_agent,\n",
    "    message=api_task,\n",
    "    max_turns=10,\n",
    ")\n",
    "\n",
    "print(\"\\n\" + \"=\" * 50)\n",
    "print(\"Cryptocurrency Analysis Completed!\")\n",
    "print(\"=\" * 50)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Example 3: Using Factory Pattern\n",
    "\n",
    "AG2 also supports creating YepCode executors using the factory pattern for more convenient configuration.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from autogen.coding import CodeExecutorFactory\n",
    "\n",
    "# Create YepCode executor using factory\n",
    "factory_executor = CodeExecutorFactory.create({\n",
    "    \"executor\": \"yepcode\",\n",
    "    \"yepcode\": {\n",
    "        \"timeout\": 90,\n",
    "        \"remove_on_done\": True,  # Clean up after execution\n",
    "        \"sync_execution\": True,\n",
    "    },\n",
    "})\n",
    "\n",
    "# Create agent with factory-created executor\n",
    "factory_agent = ConversableAgent(\n",
    "    \"factory_agent\",\n",
    "    llm_config=False,\n",
    "    code_execution_config={\"executor\": factory_executor},\n",
    "    human_input_mode=\"NEVER\",\n",
    ")\n",
    "\n",
    "# Test quick calculation\n",
    "math_task = \"\"\"\n",
    "Calculate the following using Python:\n",
    "```python\n",
    "import math\n",
    "\n",
    "# Calculate compound interest\n",
    "principal = 10000  # Initial investment\n",
    "rate = 0.07        # 7% annual interest\n",
    "time = 10          # 10 years\n",
    "n = 4              # Compounded quarterly\n",
    "\n",
    "amount = principal * (1 + rate/n)**(n*time)\n",
    "interest_earned = amount - principal\n",
    "\n",
    "print(f\"Principal: ${principal:,.2f}\")\n",
    "print(f\"Final Amount: ${amount:,.2f}\")\n",
    "print(f\"Interest Earned: ${interest_earned:,.2f}\")\n",
    "\n",
    "return {\n",
    "    'principal': principal,\n",
    "    'final_amount': round(amount, 2),\n",
    "    'interest_earned': round(interest_earned, 2)\n",
    "}\n",
    "```\n",
    "\"\"\"\n",
    "\n",
    "result = factory_agent.generate_reply(messages=[{\"role\": \"user\", \"content\": math_task}])\n",
    "print(result)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Summary\n",
    "\n",
    "This notebook demonstrated the key features of the YepCode Executor for AG2:\n",
    "\n",
    "### Key Features Covered:\n",
    "1. **Basic Setup**: How to create and configure YepCode executors\n",
    "2. **Multi-Language Support**: Python and JavaScript execution\n",
    "3. **AI Agent Integration**: Using YepCode with AI agents for code generation and execution\n",
    "4. **Automatic Dependencies**: NPM and PyPI packages installed automatically\n",
    "5. **Factory Pattern**: Using the CodeExecutorFactory for convenience\n",
    "\n",
    "### Benefits of YepCode:\n",
    "- **Serverless**: No infrastructure management required\n",
    "- **Secure**: Isolated sandbox environments\n",
    "- **Scalable**: Production-grade execution platform\n",
    "- **Developer Friendly**: Automatic dependency management\n",
    "- **Multi-Language**: Python and JavaScript support\n",
    "- **Enterprise Ready**: Built for production workloads\n",
    "\n",
    "### Next Steps:\n",
    "1. Get your YepCode API token at [yepcode.io](https://yepcode.io)\n",
    "2. Install AG2 with YepCode support: `pip install ag2[yepcode]`\n",
    "3. Start building powerful AI agents with serverless code execution!\n",
    "\n",
    "For more information:\n",
    "- [YepCode Documentation](https://yepcode.io/docs)\n",
    "- [AG2 Documentation](https://docs.ag2.ai)\n",
    "- [AG2 Code Execution Guide](https://docs.ag2.ai/latest/docs/user-guide/advanced-concepts/code-execution)\n"
   ]
  }
 ],
 "metadata": {
  "colab": {
   "provenance": []
  },
  "front_matter": {
   "description": "Use AG2 to execute code with YepCode",
   "tags": [
    "llm",
    "openai",
    "yepcode"
   ]
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
